package com.guguskins.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.common.constant.PropConstant;
import com.guguskins.back.entity.GuProp;
import com.guguskins.back.entity.GuPropNum;
import com.guguskins.back.entity.GuUser;
import com.guguskins.back.mapper.GuPropNumMapper;
import com.guguskins.back.service.GuPropNumService;
import com.guguskins.back.service.GuPropService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-05-24
 */
@Service
public class GuPropNumServiceImpl extends ServiceImpl<GuPropNumMapper, GuPropNum> implements GuPropNumService {

    @Autowired
    private GuPropNumMapper propNumMapper;

    @Autowired
    private GuPropService propService;

    @Override
    public List<GuPropNum> getBySteamId(String steamId) {

        return this.list(new LambdaQueryWrapper<GuPropNum>() {
            {
                eq(GuPropNum::getSteamId, steamId);
            }
        });
    }

    @Override
    public GuPropNum getByUserIdAndPropId(Long userId, int propId) {
        return this.getOne(new LambdaQueryWrapper<GuPropNum>() {
            {
                eq(GuPropNum::getUserId, userId);
                eq(GuPropNum::getPropId, propId);
            }
        });
    }

    @Override
    public boolean init(GuUser user) {
        List<GuProp> props = propService.list(new LambdaQueryWrapper<GuProp>() {
            {
                notIn(GuProp::getPropId, PropConstant.GU_CURRENCY, PropConstant.EXTEND_HEN_HOUSE);
            }
        });
        List<GuPropNum> propNums = new ArrayList<>();
        props.forEach(prop -> {
            GuPropNum propNum = new GuPropNum();
            propNum.setUserId(user.getUserId());
            propNum.setSteamId(user.getUserSteamId());
            propNum.setPropId(prop.getPropId());
            propNum.setPropNum(prop.getPropId().equals(PropConstant.HEN_HOUSE) ? 1 : 0);
            propNums.add(propNum);
        });
        return this.saveBatch(propNums);
    }

    @Override
    public void addPropNum(Long userId, Long propId) {
        GuPropNum propNum = this.getOne(new LambdaQueryWrapper<GuPropNum>() {
            {
                eq(GuPropNum::getUserId, userId);
                eq(GuPropNum::getPropId, propId);
                last("limit 1");
            }
        });
        propNum.setPropNum(propNum.getPropNum() + 1);
        propNum.updateById();
    }
}
